package com.zhht.htzx.utils;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.text.TextUtils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.zhht.htzx.model.Order;

import java.util.HashMap;
import java.util.Map;

/**
 * 二维码生成工具类
 */
public class QRCodeGenerator {
    
    /**
     * 生成订单二维码
     * @param order 订单对象
     * @param size 二维码尺寸
     * @return 二维码Bitmap
     */
    public static Bitmap generateOrderQRCode(Order order, int size) {
        if (order == null || TextUtils.isEmpty(order.getOrderId())) {
            return null;
        }
        
        // 构建订单信息JSON字符串
        String orderInfo = buildOrderInfo(order);
        
        return generateQRCode(orderInfo, size);
    }
    
    /**
     * 生成普通文本二维码
     * @param content 二维码内容
     * @param size 二维码尺寸
     * @return 二维码Bitmap
     */
    public static Bitmap generateQRCode(String content, int size) {
        if (TextUtils.isEmpty(content)) {
            return null;
        }
        
        try {
            // 设置二维码参数
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.M);
            hints.put(EncodeHintType.MARGIN, 1);
            
            // 创建二维码写入器
            QRCodeWriter writer = new QRCodeWriter();
            BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, size, size, hints);
            
            // 转换为Bitmap
            Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565);
            for (int x = 0; x < size; x++) {
                for (int y = 0; y < size; y++) {
                    bitmap.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);
                }
            }
            
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 构建订单信息JSON字符串
     */
    private static String buildOrderInfo(Order order) {
        StringBuilder json = new StringBuilder();
        json.append("{");
        json.append("\"orderId\":\"").append(order.getOrderId()).append("\",");
        json.append("\"status\":\"").append(order.getStatus().getDisplayName()).append("\",");
        json.append("\"totalAmount\":").append(order.getActualAmount()).append(",");
        json.append("\"createTime\":\"").append(order.getCreateTime().getTime()).append("\",");
        json.append("\"receiverName\":\"").append(order.getReceiverName() != null ? order.getReceiverName() : "").append("\",");
        json.append("\"receiverPhone\":\"").append(order.getReceiverPhone() != null ? order.getReceiverPhone() : "").append("\",");
        json.append("\"address\":\"").append(order.getAddress() != null ? order.getAddress() : "").append("\"");
        json.append("}");
        
        return json.toString();
    }
    
    /**
     * 生成带Logo的二维码
     * @param content 二维码内容
     * @param size 二维码尺寸
     * @param logoBitmap Logo图片
     * @return 带Logo的二维码Bitmap
     */
    public static Bitmap generateQRCodeWithLogo(String content, int size, Bitmap logoBitmap) {
        Bitmap qrCodeBitmap = generateQRCode(content, size);
        if (qrCodeBitmap == null || logoBitmap == null) {
            return qrCodeBitmap;
        }
        
        try {
            // 计算Logo尺寸（二维码的1/4）
            int logoSize = size / 4;
            
            // 缩放Logo
            Bitmap scaledLogo = Bitmap.createScaledBitmap(logoBitmap, logoSize, logoSize, true);
            
            // 计算Logo位置（居中）
            int left = (size - logoSize) / 2;
            int top = (size - logoSize) / 2;
            
            // 创建画布并绘制二维码和Logo
            android.graphics.Canvas canvas = new android.graphics.Canvas(qrCodeBitmap);
            canvas.drawBitmap(scaledLogo, left, top, null);
            
            return qrCodeBitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return qrCodeBitmap;
        }
    }
} 